<?php
/**
 * Created by xiaosong
 * E-mail:306027376@qq.com
 * Date: 2018/11/14
 * Time: 16:14
 */

namespace app\api\controller;
use app\common\logic\Logic;
use app\common\logic\SkillApply;
use app\common\model\SkillApply as apply;
use app\common\model\Order;
use app\common\model\Skill as model;
use GatewayWorker\Lib\Gateway;
use think\Db;
use think\Exception;

class Skill extends User
{


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 添加资质
     */
    public function skill()
    {

        $model = new model();

        $data['my']   = (new apply())->getMy(['u.user_id' => $this->user_id]);

        $data['game'] = $model->getRows(['type'=>2]);
        $data['fun']  = $model->getRows(['type'=>1]);

        api_return(1,'获取成功',$data);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 资质管理
     */
    public function skills()
    {

        $rows = (new apply())->getMy(['u.user_id' => $this->user_id]);

        api_return(1,'获取成功',$rows);

    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 资质申请详情页
     */
    public function detail()
    {

        $id = input('post.id');

        if (!is_numeric($id)) api_return(0,'参数错误');

        $map['skill_id'] = $id;

        $data['skill'] = Db::name('skill')
            ->where($map)
            ->field('skill_id,request,skill_name,explain,header_exp,skill_img,video,grade,video_img')
            ->cache(30)
            ->find();

        if (!$data['skill']) api_return(0,'非法参数');

        $data['skill']['grade'] = explode(',',$data['skill']['grade']);

        $map['user_id'] = $this->user_id;

        $data['my'] = Db::name('skill_apply')->where($map)->field('img,video,voice,explain,status,my_grade')->find();

        $data['header_img'] = $this->userInfo('header_img');

        api_return(1,'获取成功',$data);

    }


    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 资质申请
     */
    public function apply()
    {

        $this->ApiLimit(2,$this->user_id);

        $data = request()->only(['skill_id','img','video','voice','explain','is_use','my_grade','video_img'],'post');

        $where['skill_id'] = $data['skill_id'];
        $where['status']   = 1;

        $skill = Db::name('skill')->where($where)->value('skill_id');

        if (!$skill) api_return(0,'禁止申请');

        $map['skill_id'] = $data['skill_id'];
        $map['user_id']  = $this->user_id;

        $model = new SkillApply();

        $apply = $model->where($map)->find();

        if ($apply){

            if ($apply['status'] == 0){
                api_return(0,'您的资质申请还在审核中,请勿重复操作');
            }else{
                $data['id'] = $apply['apply_id'];
            }

        }else{
            $skillInfo = Db::name('skill')->where('skill_id',$data['skill_id'])->cache(60)->find();
            $data['my_gift_id'] = $skillInfo['gift_id'];
            $data['my_form']    = $skillInfo['form_id'];

//            $gift['gift_id'] = ['in',$skillInfo['gift_id']];
//            $gift['status']  = 1;
//            $data['mini_price'] = Db::name('gift')->where($gift)->order('price')->value('price');

            $data['mini_price'] = getMiniPrice($skillInfo['gift_id']);

        }
        $data['user_id'] = $this->user_id;

        $result = $model->saveChange($data);

        if ($result){
            api_return(1,'提交成功,请等待管理员审核');
        }
        api_return(0,$model->getError());
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 资质上下架
     */
    public function shelf(int $id,int $is_use)
    {

        $map['skill_id'] = $id;
        $map['user_id']  = $this->user_id;
        $map['status']   = 1;

        $model = new SkillApply();

        $data  = $model->where($map)->find();

        if ($data){

            $result = $data->validate('base.skill_shelf')->save(['is_use'=>$is_use]);

            if ($result){

                api_return(1,'修改成功');

            }

            api_return(0,$data->getError());

        }else{

            api_return(0,'参数错误');

        }

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 资质设置--显示页
     */
    public function setSkill()
    {

        $id = input('post.id');
        if (!is_numeric($id)) api_return(0,'缺少技能id');

        $map['a.user_id']  = $this->user_id;
        $map['a.status']   = 1;
        $map['a.is_use']   = 1;
        $map['s.skill_id'] = $id;

        $model = new apply();

        $data['rows']  = $model->getRows($map);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 技能编辑
     */
    public function editSkill()
    {

        $data = request()->only(['my_form','my_gift_id','apply_id'],'post');

        $map['apply_id'] = $data['apply_id'];
        $map['status']   = 1;
        $map['user_id']  = $this->user_id;

        $model = new apply();

        $row = $model->where($map)->find();

        if (!$row) api_return(0,'非法参数');

        $where['skill_id'] = $row['skill_id'];

        $skill = Db::name('skill')->where($where)->find();

        $gift_ids = explode(',',$data['my_gift_id']);

        foreach ($gift_ids as $v){
            if (!strstr($skill['gift_id'],$v)) api_return(0,'礼物id错误');
        }

        $data['mini_price'] = getMiniPrice($data['my_gift_id']);

        $result = $row->update($data);

        if ($result !== false){
            api_return(1,'修改成功');
        }else{
            api_return(0,$model->getError());
        }

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 技能详情
     */
    public function skillDetail()
    {
        $id = input('post.id');

        $map['a.status']   = 1;
        $map['a.apply_id'] = $id;

        $model = new apply();

        $data  = $model->detail($map);

        $data['is_follow'] = self::isFollow($this->user_id,dehashid($data['user_id']));

        api_return(1,'获取成功',$data);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据申请id   获取用户技能申请详情
     */
    protected function getApply()
    {
        $id = input('post.id');

        $map['status']   = 1;
        $map['apply_id'] = $id;

        return Db::name('skill_apply')->where($map)->cache(15)->find();
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 技能详情 -- 技能统计
     */
    public function skillCount()
    {

        $data = $this->getApply();

        $form['a.skill_id'] = $data['skill_id'];
        $form['a.user_id']  = $data['user_id'];
        $form['a.status']   = 1;
        $form['s.status']   = 1;

        $rows['forms'] = Db::name('skill_form_user')->alias('a')
            ->join('skill_form s','s.form_id = a.form_id','LEFT')
            ->where($form)
            ->order('a.num desc')
            ->field('a.num,s.form_name')
            ->cache(15)
            ->select();

        $tag['a.skill_id'] = $data['skill_id'];
        $tag['a.user_id']  = $data['user_id'];
        $tag['a.status']   = 1;
        $tag['t.status']   = 1;

        $rows['tags'] = Db::name('skill_tag_user')->alias('a')
            ->join('skill_tag t','t.tag = a.tag','LEFT')
            ->where($tag)
            ->order('a.num desc')
            ->field('a.num,t.tag_name')
            ->cache(15)
            ->select();

        $map['to_user']  = $data['user_id'];
        $map['skill_id'] = $data['skill_id'];
        $map['status']   = 5;

        $rows['count'] = self::orderCount($map);

//        $rows['count']['num'] = Db::name('order')->where($map)->count('order_id');
//
//        $score = Db::name('order')->where($map)->avg('score');
//
//        $rows['count']['score'] = numberDecimal($score);

        api_return(1,'获取成功',$rows);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 技能详情--技能评论
     */
    public function skillComment()
    {

        $data = $this->getApply();

        $map['a.to_user']  = $data['user_id'];
        $map['a.skill_id'] = $data['skill_id'];
        $map['a.status']   = 5;

        $model = new Order();

        $rows  = $model->getComment($map);

        api_return(1,'获取成功',$rows);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 邀约界面
     */
    public function invite()
    {
        $id = dehashid(input('post.id'));
        if (!is_numeric($id)) api_return(0,'参数错误');

        $rows['userInfo'] = $this->userInfo('nick_name,header_img',$id);

        $map['a.user_id'] = $id;
        $map['a.is_use']  = 1;
        $map['a.status']  = 1;

        $model = new apply();

        $rows['rows'] = $model->getRows($map,true);

        api_return(1,'获取成功',$rows);

    }

    public function test()
    {
        dd(cache('testdata'));
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 下单
     */
    public function order()
    {

        $this->ApiLimit(1,$this->user_id);

        $data = request()->only(['skill_id','to_user','form_id','gift_id','num','order_time','type','remark'],'post');
        $to_user = dehashid($data['to_user']);

        if (!is_numeric($to_user)) api_return(0,'参数错误');

        if ($to_user == $this->user_id){
            api_return(0,'您不能向自己下单');
        }

        $data['to_user'] = $to_user;
        $map['status']   = 1;
        $map['user_id']  = $to_user;
        $map['is_use']   = 1;
        $map['skill_id'] = $data['skill_id'];

        $apply = Db::name('skill_apply')->where($map)->find();

        if (!$apply) api_return(0,'用户无此技能');

        if (!strstr($apply['my_form'],$data['form_id'])) api_return(0,'用户不接受此邀约形式');
        if (!strstr($apply['my_gift_id'],$data['gift_id'])) api_return(0,'用户不接受此礼物');
        if (!isInt($data['num'])) api_return(0,'数量错误');

        $where['gift_id'] = $data['gift_id'];
        $where['status']  = 1;
        $price = Db::name('gift')->where($where)->value('price');
        if (!$price) api_return(0,'礼物信息错误');

        $data['price'] = bcmul($price,$data['num'],2);

        $data['user_id'] = $this->user_id;

        Db::startTrans();
        try{
            //余额支付
            if ($data['type'] == 'integral'){

                $this->moneyDec($data['price']);

                $data['status'] = 1;
            }

            $model = new Logic();

            $result = $model->saveChange('order',$data,'order.add');

            if (!$result){

                api_return(0,$model->getError());

            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,'服务器繁忙,请稍后重试',$e->getMessage());
        }

        $order['a.order_id'] = $model->order_id;

        $row = $this->orderDetail($order);

        api_return(1,'下单成功',$row);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 接单记录
     */
    public function receipt()
    {
        $type = input('type');
        $join = [
            [ 'skill_form sf','sf.form_id = a.form_id','LEFT'],
            [ 'skill s','s.skill_id = a.skill_id','LEFT'],
        ];
        if ($type == 'receipt'){
            $map['a.to_user'] = $this->user_id;
            $join[] = ['users u','u.user_id = a.user_id'];
        }else{
            $map['a.user_id'] = $this->user_id;
            $join[] = ['users u','u.user_id = a.to_user'];
        }

        $model = new Order();

        $rows = $model->getRows($map,$join);

        api_return(1,'获取成功',$rows);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 邀约详情
     */
    public function inviteDetail()
    {

        $id = input('post.id');
        if (!is_numeric($id)) api_return(0,'参数错误');
        $map['a.order_id'] = $id;

        $data = $this->orderDetail($map);

        api_return(1,'获取成功',$data);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单详情
     */
    protected  function orderDetail(array $map)
    {
        $model = new Order();

        $data  = $model->getOne($map);

        if (!$data){
            api_return(0,'非法参数');
        }
        $data['order_time'] = formatTime($data['order_time']);
//        $data['order_time'] = formatTime(time()+86400);
        if ($data['user_id'] == $this->user_id){

            $data['nick_name']  = $this->userInfo('nick_name',$data['to_user']);
            $data['header_img'] = $this->userInfo('header_img',$data['to_user']);
            $data['level']      = $this->userExtra('level',$data['to_user']);

        }elseif($data['to_user'] == $this->user_id){

            $data['nick_name']  = $this->userInfo('nick_name',$data['user_id']);
            $data['header_img'] = $this->userInfo('header_img',$data['user_id']);
            $data['level']      = $this->userExtra('level',$data['user_id']);

        }else{
            api_return(0,'非法参数');
        }

        $data['user_id'] = hashid($data['user_id']);
        $data['to_user'] = hashid($data['to_user']);
        $data['self']    = hashid($this->user_id);

        return $data;
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单取消
     */
    public function orderCancel()
    {

        $id = input('post.id');

        if (!is_numeric($id)) api_return(0,'参数错误');

        $result = self::refund($id);
        if ($result === true)
            api_return(1,'取消订单成功,已退款至付款账户');
        api_return(0,$result);

    }





    /**
     * 订单确认
     */
    public function confirm()
    {
        $id = input('post.id');

        if (!isInt($id)) api_return(0,'参数错误');

        $model = new Order();

        $map['status']   = 1;
        $map['to_user']  = $this->user_id;
        $map['order_id'] = $id;

        $data = $model->where($map)->find();

        if (!$data) api_return(0,'订单查询错误');

        $result = $data->save(['status'=>2]);

        if ($result){
            $title = '和 '.$this->userInfo('nick_name',$data['user_id'].' '.getSkillName($data['skill_id']).' 确认');
            money_detail(1,$this->user_id,$title,$data['price'],'锁定');
            api_return(1,'订单确认成功');

        }

        api_return(0,$data->getError());

    }

    /**
     * 订单开始
     */
    public function start()
    {
        $id = input('post.id');
        if (!isInt($id)) api_return(0,'参数错误');
        $model = new Order();
        $map['status']   = 2;
        $map['user_id']  = $this->user_id;
        $map['order_id'] = $id;
        $data = $model->where($map)->find();
        if (!$data) api_return(0,'订单查询错误');
        $result = $data->save(['status'=>3]);
        if ($result){
            api_return(1,'订单开始成功');
        }
        api_return(0,$data->getError());
    }


    /**
     * 订单完成
     */
    public function finish()
    {
        $id = input('post.id');
        if (!isInt($id)) api_return(0,'参数错误');
        $map['status']   = 3;
        $map['user_id']  = $this->user_id;
        $map['order_id'] = $id;
        $order = Db::name('order')->where($map)->find();
        if (!$order) api_return(0, '订单查询错误');
        $result = self::complete($order);
        if ($result === true){
            api_return(1,'订单完成');
        }
        api_return(0,$result);
    }


    
    
    

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单退款申请
     */
    public function refundApply()
    {

        $id     = input('post.id');
        $reason = input('post.reason');

        if (!isInt($id)) api_return(0,'参数错误');

        if (empty($reason)) api_return(0,'退款原因必须填写');

        $model = new Order();

        $map['status']   = 3;
        $map['user_id']  = $this->user_id;
        $map['order_id'] = $id;

        $data = $model->where($map)->find();
        if (!$data) api_return(0,'订单查询错误');

        $result = $data->save(['status'=>7,'reason'=>$reason]);

        if ($result){

            api_return(1,'退款申请成功');

        }

        api_return(0,$data->getError());

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单退款申请审核
     */
    public function check()
    {
        $id     = input('post.id');

        $status = input('post.status');

        if ($status != 11 && $status != 8) api_return(0,'类型错误');

        if (!isInt($id)) api_return(0,'参数错误');

        $model = new Order();

        $map['status']   = 7;
        $map['to_user']  = $this->user_id;
        $map['order_id'] = $id;

        $data = $model->where($map)->find();
        if (!$data) api_return(0,'订单查询错误');



        if ($status == 11){ //退款申请通过
            $result = self::refund($id,$status);
            if ($result !== true){
                api_return(0,$result);
            }else{
                api_return(1,'退款成功');
            }
        }else{
            $result = $data->save(['status'=>$status]);
            if ($result){
                api_return(1,'退款驳回成功');
            }
            api_return(0,$data->getError());
        }
    }


    public function protest(int $id)
    {
        $map['order_id'] = $id;
        $map['user_id']  = $this->user_id;
        $map['status']   = 8;

        $model = new Order();

        $data = $model->where($map)->find();
        if (!$data){
            api_return(0,'订单查询错误');
        }

        $result = $data->save(['status'=>9]);

        if ($result !== false){
            api_return(1,'申请成功,请与客服联系或耐心等待管理员审核');
        }
        api_return(0,$data->getError());

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单评价页面
     */
    public function evaluateView(int $id)
    {

        $map['a.order_id'] = $id;
        $map['a.user_id']  = $this->user_id;
        $map['a.status']   = 4;

        $model = new Order();

        $data = $model->evaluateInfo($map);
        if (!$data){
            api_return(0,'订单查询错误');
        }

        $data['noble_id'] = self::checkNoble($data);

        $data['order_time'] = formatTime($data['order_time']);

        $data['tags'] = getSkillTags($data['tag'],true);

        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 订单评价
     */
    public function anonymous()
    {

        $data = request()->only(['id','score','tags','anonymous','content'],'post');

        $map['order_id'] = $data['id'];
        $map['user_id']  = $this->user_id;
        $map['status']   = 4;

        $model = new Order();

        $order = $model->where($map)->find();
        if (!$order){
            api_return(0,'订单查询错误');
        }

        $where['skill_id'] = $order['skill_id'];
        $where['user_id']  = $order['to_user'];

        $apply = Db::name('skill_apply')->where($where)->field('score,score_num,apply_id')->find();
        $score_num = $apply['score_num']+1;
        $score = bcdiv(bcmul($apply['score'],$apply['score_num'],2)+$order['score'],$score_num,1);

        $change['score'] = $score;
        $change['score_num'] = $score_num;
        $change['update_time'] = time();

        $tags = explode(',',$data['tags']);

        $tag['skill_id'] = $order['skill_id'];
        $tag['user_id']  = $order['to_user'];

        Db::startTrans();
        try{

            //订单表修改
            $data['status'] = 5;
            $result = $order->validate('order.evaluate')->allowField(true)->save($data);
            if ($result === false){
                api_return(0,$order->getError());
            }

            //修改用户技能统计数据
            Db::name('skill_apply')->where('apply_id',$apply['apply_id'])->update($change);

            //修改用户技能评论标签
            $insert_tag = [];
            foreach ($tags as $k => $v){

                $tag['tag'] = $v;
                $user_tag = Db::name('skill_tag_user')->where($tag)->find();
                if ($user_tag){
                   Db::name('skill_tag_user')->where('id',$user_tag['id'])->setInc('num');
                }else{
                    $tag['num'] = 1;
                    $tag['create_time'] = time();
                    $tag['update_time'] = time();
                    $insert_tag[] = $tag;
                }
            }

            if ($insert_tag){
                Db::name('skill_tag_user')->insertAll($insert_tag);
            }

            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,$e->getMessage());
        }

        api_return(1,'评价成功');
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 闪电邀约
     */
    public function fastOrder()
    {

        $this->ApiLimit(5,$this->user_id);

        $data = request()->only(['skill_id','order_time','grade','tag','type','room_id','form_ids'],'post');

        $model = new apply();

        $map['e.invite'] = 1;
        $map['e.online_status'] = 1;

        if (isInt($data['skill_id'])){
            $map['a.skill_id'] = $data['skill_id'];
        }else{
            api_return(0,'技能id错误');
        }

        if ($data['grade']){
            if (strstr($data['grade'],',')){
                $map['a.my_grade'] = ['in',$data['grade']];
            }else{
                $map['a.my_grade'] = $data['grade'];
            }
        }

        if($data['tag']){
            if (strstr($data['tag'],',')){
                $map['a.tag'] = ['in',$data['tag']];
            }else{
                $map['a.tag'] = $data['tag'];
            }
        }

        if ($data['form_ids']){
            $array = explode(',',$data['form_ids']);
            foreach ($array as $k => $v){
                $map['a.my_form'][] = ['like',$v.'%'];
            }
        }

        $rows = $model->getFast($map);
//        dump($model->getLastSql());
        $data['user_id'] = $this->user_id;
        if ($rows){

            $response['group_id']    = hashid($this->user_id);
            $response['skill_name']  = $rows[0]['skill_name'];
            $response['order_time']  = formatTime($data['order_time'],false);
            $response['create_time'] = time();
            $response['tag']         = $data['tag'];
            $response['grade']       = $data['grade'];
            $response['nick_name']   = $this->userInfo('nick_name');
            $response['header_img']   = $this->userInfo('header_img');

            foreach ($rows as $k => $v){
                var_dump($v['user_id']);
                //缓存下用户发起闪电邀约的数据
                //TODO 测试阶段闪电邀约过期时间不过期  上线后改为360s
                cache('fastOrder_'.hashid($this->user_id),$data);
                $res = $this->sendUsrMsg(hashid($v['user_id']),1,$response);
                //判断是否为点单房间里的点单消息
                if ($data['type'] == 'order'){
                    setOrderRoom($data['room_id']);
                }
            }
            api_return(1,'闪电邀约发起成功',hashid($this->user_id));
        }else{
            api_return(0,'当前无合适用户在线');
        }

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 接受闪电邀约
     */
    public function accept()
    {
        $group_id = input('post.group_id');

        $data = cache('fastOrder_'.$group_id);

        if (!$data){
            api_return(0,'已结束邀请');
        }

        api_return(1,'接受邀请成功,连接socket');
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 闪电邀约取消
     */
    public function cancel()
    {
        $hash = hashid($this->user_id);

        Events::groupResponse(400,$hash,'闪电邀约取消');

        Gateway::ungroup($hash);

        api_return(1,'取消成功');
    }
    
}